import init from "./model";
import { scannerDecoration, registerControllerToRouter } from 'ts-express-restful';
import * as http from 'http';
import express from 'express';
import * as path from 'path';
import * as net from 'net';
import { Request, Response } from "express-serve-static-core";
import { NextFunction } from "connect";
import CustomerError from "./error";
import serveStatic = require("serve-static");
import bodyParser = require("body-parser");

async function initDB() { 
    return init({
        dialect: 'postgres',
        username: 'postgres',
        password: 'root',
        database: 'pig-cms',
        sync: false,
    });
}

async function initHttpServer() { 
    const app = express();
    app.use(serveStatic(path.join(__dirname, '../front/build')));
    app.use(bodyParser.json())
    app.use((req: Request, res: Response, next: NextFunction) => { 
        res.header("Access-Control-Allow-Origin", "*");
        res.header('Access-Control-Allow-Methods', 'DELETE, POST, GET, PUT, OPTIONS');
        res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        next();
    })
    const router = express.Router();
    scannerDecoration(path.resolve(__dirname, 'controller'), [/\.d\.ts$/]);
    registerControllerToRouter(router, { isShowUrls: true });
    const adminRouter = express.Router();
    registerControllerToRouter(adminRouter, { group: 'admin' , isShowUrls: true});
    app.use((req: Request, res: Response, next: NextFunction) => { 
        req.query.lang = 'en'
        next();
    })
    app.use('/', router);
    app.use('/admin', adminRouter);
    const server = http.createServer(app);
    server.on('listening', () => { 
        const port = server.address() && (server.address() as net.AddressInfo).port;
        console.log('http server listen on ', port);
    })
    server.listen(4000);

    app.use(function (err: any, req: Request, res: Response, next: NextFunction) { 
        if (err instanceof CustomerError) { 
            res.statusCode = err.code;
            res.send(err.msg);
            return;
        }
        console.error(err.stack);
        res.statusCode = 500;
        res.send("服务器内部错误,请稍后重试");
    })
}

async function main() { 
    await initDB();
    await initHttpServer();
}


main()
    .catch((err) => { 
        console.error(err);
        process.exit(-1);
    })